package main

import (
	"flag"
	"fmt"
	"net/http"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 版本信息，通过编译时注入
var (
	Version   = "dev"
	BuildDate = "unknown"
	GitCommit = "unknown"
	GitBranch = "unknown"
)

var configFile = flag.String("f", "etc/api.yaml", "the config file")

func main() {
	flag.Parse()

	var c rest.RestConf
	conf.MustLoad(*configFile, &c)

	// 设置日志级别
	setupLogger(c)

	server := rest.MustNewServer(c)
	defer server.Stop()

	// 注册路由
	setupRoutes(server)

	// 注册错误处理函数
	httpx.SetErrorHandler(errorHandler)

	fmt.Printf("Starting %s server at %s:%d (version: %s, commit: %s)\n",
		"AI-Offer API", c.Host, c.Port, Version, GitCommit)
	server.Start()
}

func setupLogger(c rest.RestConf) {
	// 配置日志
	logx.MustSetup(c.Log)
	logx.Info("Logger setup successfully")
}

func setupRoutes(server *rest.Server) {
	// 健康检查路由
	server.AddRoute(rest.Route{
		Method: http.MethodGet,
		Path:   "/health",
		Handler: func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("OK"))
		},
	})

	// 版本信息路由
	server.AddRoute(rest.Route{
		Method: http.MethodGet,
		Path:   "/version",
		Handler: func(w http.ResponseWriter, r *http.Request) {
			info := map[string]string{
				"version":   Version,
				"buildDate": BuildDate,
				"gitCommit": GitCommit,
				"gitBranch": GitBranch,
			}
			httpx.OkJson(w, info)
		},
	})
}

func errorHandler(err error) (int, interface{}) {
	// 自定义错误处理
	logx.Errorf("Error: %v", err)

	return http.StatusInternalServerError, map[string]interface{}{
		"code":    500,
		"message": err.Error(),
	}
}
